package com.guapi.controller.interceptor;

import com.guapi.entity.Goods;
import com.guapi.entity.LoginTicket;
import com.guapi.entity.User;
import com.guapi.service.GoodsService;
import com.guapi.service.UserService;
import com.guapi.util.CookieUtil;
import com.guapi.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private HostHolder hostHolder;

    private static final Logger logger = LoggerFactory.getLogger(LoginTicketInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request, "ticket");
        //logger.warn("ticket:"+ticket);
        if (ticket != null) {
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //检查是否过期
            if (loginTicket != null && loginTicket.getExpired().after(new Date()) && loginTicket.getStatus() == 1) {
                User user = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user);

                //logger.info("存入了user"+user);

                //暂时不存入SpringbootSecurity
                //Authentication authentication = new UsernamePasswordAuthenticationToken(
                //        //用户，用户的认证，用户权限
                //        user, user.getPassword(), userService.getAuthorities(user.getId())
                //);
                ////存入权限
                //SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        long sumPrice = 0;
        if (user != null && modelAndView != null) {
            Set<Goods> goodsSet = goodsService.getCartGoods(user);
            ArrayList<HashMap<String, Object>> goodsSellerList = new ArrayList<>();
            if (goodsSet.size() != 0) {
                for (Goods goods : goodsSet) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("goods", goods);
                    map.put("userName", userService.findUserById(goods.getUserId()).getUserName());
                    sumPrice += goods.getPrice();
                    goodsSellerList.add(map);
                }
            }

            modelAndView.addObject("goodsSellerList",goodsSellerList);
            modelAndView.addObject("setSize", goodsSet.size());
            modelAndView.addObject("sumPrice", sumPrice);
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        hostHolder.clear();
    }
}
